package com.example.demo.util;


import com.example.demo.exception.AgyException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * hibernate-validator校验工具类
 *
 * @author BleethNie
 * @version 1.0
 * @date 2020-01-08 16:12
 **/
public class ValidatorUtil {
    private static final Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws AgyException 校验不通过，则报ShoppingException异常
     */
    public static void validateEntity(Object object, Class<?>... groups)  throws AgyException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            ConstraintViolation<Object> constraint = (ConstraintViolation<Object>) constraintViolations.iterator().next();
            throw new AgyException("参数校验不合法:"+constraint.getMessage());
        }
    }
}
